import { convertObj2KV } from './util.js'

let socket = null;
let socketClosed = true;
let handleMessage = () => {};
let timer = null;
// 心跳频率：10秒
const HEART_RATE = 10 * 1e3;
const WS_URL = 'cloudmeetingcs.quanyou.com.cn:8319';
let clientVersion = 'yoyo-meeting-uni-1.0.0';

const onOpen = () => {
  console.log('socket opened...');
  socketClosed = false;
  sendHeartbeat();
}

const onMessage = (event) => {
  console.log('receive message: ', event.data);
  // const data = JSON.parse(event.data);
  handleMessage(event.data);
}

const onError = (error) => {
  console.log('socket error: ', error);
  socketClosed = true;
}

const onClose = (event) => {
  console.log('socket closed...');
  socketClosed = true;
}

function addListener() {
  if (!socket) {
    return;
  }
  
  // 建立连接
  socket.addEventListener('open', onOpen);
  // 接收消息
  socket.addEventListener('message', onMessage);
  // 连接错误关闭
  socket.addEventListener('error', onError);
  // 连接关闭
  socket.addEventListener('close', onClose);
}

function removeListener() {
  if (!socket) {
    return;
  }
  socket.removeEventListener('open', onOpen);
  socket.removeEventListener('message', onMessage);
  socket.removeEventListener('error', onError);
  socket.removeEventListener('close', onClose);
}

// 发送心跳消息
function sendHeartbeat() {
  if (timer) {
    clearInterval(timer);
  }
  
  timer = setInterval(() => {
    ws.send({
      cmd: 6,
      t: Date.now()
    });
  }, HEART_RATE);
}

const ws = {
  open(meetingId, msgCallback) {
    const {token, deviceCode} = getApp({allowDefault: true}).globalData;
    const params = {
      client: clientVersion,
      deviceId: deviceCode,
      token,
      meetingId,
    };
    socket = new WebSocket(`ws://${WS_URL}/?${convertObj2KV(params)}`);
    
    if (typeof msgCallback === 'function') {
      handleMessage = msgCallback;
    }
    
    addListener();
  },
  close() {
    socket && socket.close();
    removeListener();
    socket = null;
    handleMessage = () => {};
    
    if (timer) {
      clearInterval(timer);
    }
  },
  send(data) {
    if (socket && !socketClosed) {
      // data = JSON.stringify(data);
      socket.send(data);
    }
  }
}

export default ws;
